package com.bridgeintelligent.tag.engine.parse;

import com.bridgeintelligent.tag.engine.api.BaseCode;
import com.bridgeintelligent.tag.engine.api.DimInfo;
import com.bridgeintelligent.tag.engine.api.DimItemInfo;
import com.bridgeintelligent.tag.engine.api.rsp.MicroPortraitRsp;
import com.bridgeintelligent.tag.engine.core.cache.CacheConfig;
import com.bridgeintelligent.tag.engine.core.cache.CacheUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by JackCheung on 2019/10/23 12:45 AM.
 */
@Slf4j
public class MicroPortraitParse extends BaseParse {

    /**
     * 创建微观画像返回数据
     *
     * @param searchResponse searchResponses
     * @param fieldsSet      字段集
     * @return MicroPortraitRsp
     */
    public static MicroPortraitRsp create(SearchResponse searchResponse, Set<String> fieldsSet ,String symbols) {
        SearchHits searchHits = searchResponse.getHits();
        MicroPortraitRsp microPortraitRsp = new MicroPortraitRsp();
        MicroPortraitRsp.DataRsp dataRsp = new MicroPortraitRsp.DataRsp();
        dataRsp.setContent(parseHandler(searchHits, fieldsSet,symbols));
        microPortraitRsp.setCode(BaseCode.SUCCESS);
        microPortraitRsp.setData(dataRsp);
        return microPortraitRsp;
    }

    /**
     * 查询结果转换处理
     *
     * @param searchHits searchResponses
     * @param fieldsSet  字段集
     * @return List<Map   <   String   ,       String>>
     */
    private static List<Map<String, MicroPortraitRsp.DimInfo>> parseHandler(SearchHits searchHits,Set<String> fieldsSet ,String symbols) {
        SearchHit[] hits = searchHits.getHits();
        List<Map<String, MicroPortraitRsp.DimInfo>> result = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            Map<String, MicroPortraitRsp.DimInfo> map = new HashMap<>(fieldsSet.size());
            SearchHit searchHit = hits[i];
            Map<String, Object> sourceMap = searchHit.getSourceAsMap();
            parse(fieldsSet, sourceMap, map ,symbols);
            result.add(map);
        }
        return result;
    }

    /**
     * 查询缓存，把编号转换为实际的值
     *
     * @param fieldsSet fieldsSet
     * @param sourceMap sourceMap
     * @param tempMap   tempMap
     */
    static void parse(Collection<String> fieldsSet, Map<String, Object> sourceMap, Map<String, MicroPortraitRsp.DimInfo> tempMap,String symbols) {
        fieldsSet.forEach(k -> {
            Object v = sourceMap.get(k);
            k = fetchRealKey(k,symbols);
            DimInfo dimInfo = CacheUtils.getCacheInfo(CacheConfig.DIM_INFO, k);
            String dimName = Optional.ofNullable(dimInfo)
                    .map(DimInfo::getDimName)
                    .orElse(null);
            String classify = Optional.ofNullable(dimInfo)
                    .map(DimInfo::getClassify)
                    .orElse(null);

            //如果对应标签有对应item值，则从缓存中取出该值
            if (null != v) {
                String itemName;
                if(v instanceof List){
                    List<Object> values = (List<Object>) v;
                    String finalK = k;
                    itemName = values.stream().map(value->{
                        //从缓存中取出条目名
                        String temp =
                                Optional.ofNullable((DimItemInfo) CacheUtils.getCacheInfo(CacheConfig.DIM_ITEM_INFO, String.format(GROUP_FORMAT, finalK, value)))
                                .map(DimItemInfo::getDimItemName)
                                .orElse(value.toString());
                        return StringUtils.isEmpty(temp) ? value.toString() : temp;
                    }).collect(Collectors.joining(","));
                    String itemNo = values.stream().map(Object::toString).collect(Collectors.joining(","));
                    tempMap.put(k,
                            MicroPortraitRsp.DimInfo.of().setDimName(dimName).setItemName(itemName).setItemNo(itemNo).setClassify(classify));
                } else {
                    //从缓存中取出条目名
                    itemName = Optional.ofNullable((DimItemInfo) CacheUtils.getCacheInfo(CacheConfig.DIM_ITEM_INFO, String.format(GROUP_FORMAT, k, v)))
                            .map(DimItemInfo::getDimItemName)
                            .orElse(null);
                    tempMap.put(k,
                            MicroPortraitRsp.DimInfo.of().setDimName(dimName).setItemName(itemName).setItemNo(v.toString()).setClassify(classify));
                }
            } else {
                tempMap.put(k,
                        MicroPortraitRsp.DimInfo.of().setDimName(dimName).setItemName(null).setItemNo(null).setClassify(classify));
            }
        });
    }
}
